import { checkAllCart, insertCart, findCartList, deleteCart, updateCart } from '@/api/cart'

async function updateCartList (ctx) {
  // 1. 获取购物车列表
  const res = await findCartList()
  // 2. 调用mutation函数 把后端的购物车列表存入vuex state中
  ctx.commit('setCartList', res.data.result)
}

export default {
  namespaced: true,
  state: {
    cartList: []
  },
  getters: {
    // 总数量: cartList中每一项的count值做累加
    cartCount (state) {
      return state.cartList.reduce((a, c) => a + c.count, 0)
    },
    // 总价钱: cartList中每一项的单项price * count 累加起来
    allPrice (state) {
      return state.cartList.reduce((a, c) => a + c.count * c.price, 0)
    },
    // 已选择数量: cartList筛选出来selected为true的所有项count累加
    selectedCount (state) {
      return state.cartList
        .filter(item => item.selected)
        .reduce((a, c) => a + c.count, 0)
    },
    // 已选择总钱数: cartList筛选出来selected为true的所有项count * price累加
    selectedPrice (state) {
      return state.cartList
        .filter(item => item.selected)
        .reduce((a, c) => a + c.count * c.price, 0)
    },
    isAllCheck (state) {
      return state.cartList.every(item => item.selected)
    }
  },
  mutations: {
    setCartList (state, list) {
      state.cartList = list
    },
    singleCheck (state, { skuId, selected }) {
      // 1. skuId找到要修改的项
      // find -> Item  findIndex -> index
      const item = state.cartList.find(item => item.skuId === skuId)
      // 2. 把找到的项的selected字段修改为 传入的selected
      item.selected = selected
    }
  },
  actions: {
    async insertCart (ctx, { skuId, count }) {
      // 1. 添加购物车接口
      await insertCart({ skuId, count })
      updateCartList(ctx)
    },
    async delCart (ctx, ids) {
      // 1. 删除接口
      await deleteCart(ids)
      updateCartList(ctx)
    },
    async singleCheck (ctx, goods) {
      await updateCart(goods)
      updateCartList(ctx)
    },
    async allCheck (ctx, selected) {
      await checkAllCart({
        selected,
        ids: ctx.state.cartList.map(item => item.skuId)
      })
      updateCartList(ctx)
    }
  }
}
